package com.talent.web.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;

import static com.talent.web.utils.TlConstant.SSE_CACHE;

/**
 * @ClassName：SseEmitterController
 * @Author: hszhou
 * @Date: 2025/1/22 9:59
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@RestController
@RequestMapping("/sse")
public class SseEmitterController {



    @GetMapping("/connect/{clientId}")
    public SseEmitter connect(@PathVariable String clientId) throws IOException, InterruptedException {

        SseEmitter emitter = new SseEmitter(10*60*1000L);
        SSE_CACHE.put(clientId,emitter);
        emitter.send(Map.of("id",clientId,"message","连接成功"));
        emitter.onCompletion(() -> SSE_CACHE.remove(1));
        emitter.onTimeout(() -> SSE_CACHE.remove(1));



        return emitter;


    }

//    @GetMapping("/send/userId")
//    public String sendMessage(@PathVariable String clientId, @RequestParam String message) throws IOException {
//        SseEmitter emitter = SSE_CACHE.get(clientId);
//        if(emitter!=null){
//            emitter.send(Map.of("id",clientId,"message",message));
//        }
//        return "发送成功";
//    }

//    @GetMapping("/disconnect/{clientId}")
//    public String disconnect(@PathVariable String clientId){
//        SseEmitter emitter = SSE_CACHE.remove(clientId);
//        if(emitter!=null){
//            emitter.complete();
//        }
//        return "连接已经关闭";
//    }
}
